package com.study.example.question;


/**
 * @Auther: likai
 * @Date: 2021/5/19 16:24
 * @Description:  一个线程只会打印"A",一个线程只会打印"B",一个线程只会打印"C" 三个线程一起运行，交替打印，期望输出结果：ABCABCABCABC...
 */
public class Question01 {

    static volatile int tag = 0;

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                while (true){
                    if (tag%3 == 0){
                        System.out.print("A");
                        Question01.tagInc();
                    }
                }
            }
        };
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                while (true){
                    if (tag%3 == 1){
                        System.out.print("B");
                        Question01.tagInc();
                    }
                }
            }
        };
        Thread thread3 = new Thread() {
            @Override
            public void run() {
                while (true){
                    if (tag%3 == 2){
                        System.out.print("C");
                        Question01.tagInc();
                    }
                }
            }
        };
        thread1.start();
        thread2.start();
        thread3.start();
    }

    /**
     * 功能描述: tag加1原子操作
     * @param:
     * @return:
     * @auther: likai
     * @date: 2021/5/19 16:37
     */
    private static void tagInc(){
        synchronized (Question01.class){
            tag++;
            if (tag == 3000){
                tag = 0;
            }
        }
    }


}
